package com.cbtx.module_sp.ui.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.cbtx.module.base.http.HttpManager
import com.cbtx.module.base.http.MyRequestCallBack
import com.cbtx.module.base.vm.BaseVM
import com.cbtx.module.common.bean.GoodsEntity
import com.cbtx.module.common.http.HttpUrlManager
import com.cbtx.module.common.utils.DataCacheUtil
import com.cbtx.module_sp.MyApplication
import com.cbtx.module_sp.interceptor.HeaderInterceptor

class RenZhengFragmentVM(application: Application) : BaseVM(application) {

    val loadFirst = -1
    val loading = 0
    val loadEnd = 1;
    val loadError = 2;


    //    val mDatas:MutableList<RenZhengItem> = ArrayList()
    val mDatas: MutableList<GoodsEntity.DataBean.ListBean> = ArrayList()
    val mLoaderStatus: MutableLiveData<Int> = MutableLiveData()
    var mPageNo = 1;
    val mPageSize = 50

    var mCanLoadMore = false

    fun init() {
        val goodsAuthList: MutableList<GoodsEntity.DataBean.ListBean> = DataCacheUtil.readGoodsAuthList()
        if (goodsAuthList != null) {
            mDatas.addAll(goodsAuthList)
        }
    }

    fun requestData(isRefresh: Boolean) {
        mCanLoadMore = false
        if (isRefresh) {
            mPageNo = 1
        } else {
            mPageNo++
        }

        val params: MutableMap<String, Any> = HashMap()
        params["pageNum"] = mPageNo
        params["pageSize"] = mPageSize
        params["type"] = "2" //认证藏品

        HttpManager.getInstance("",
            HeaderInterceptor(MyApplication.instance.getHeaderMap())
        ).sendGet(
            HttpUrlManager.TREASURE_GOODS_LIST,
            params,
            object : MyRequestCallBack<GoodsEntity>() {
                override fun onSuccess(obj: GoodsEntity?) {
                    resetData(obj, isRefresh, true)
                }

                override fun onFailure(error: Int, msg: String?) {
                    mLoaderStatus.value = loadError
                }
            })

    }


    /**
     *
     */
    fun resetData(obj: GoodsEntity?, isRefresh: Boolean, isCacheData: Boolean) {
        val itemList: MutableList<GoodsEntity.DataBean.ListBean> = ArrayList()
        if (obj?.data != null) {
            itemList.addAll(obj.data.list)
        }

        for (renZhengItem in itemList) {
            renZhengItem.imageSmall =
                "${renZhengItem.coverImg}?x-oss-process=image/resize,m_mfit,w_200,crop,h_200,w_200,h_200,g_center"
        }

        if (isRefresh) {
            mDatas.clear()
        }

        if (itemList.size >= mPageSize) {
            mCanLoadMore = true
        }
        mDatas.addAll(itemList)

        if (isCacheData) {
            DataCacheUtil.saveGoodsAuthList(mDatas)
        }
        mLoaderStatus.value = loadEnd
    }
}